package org.goyo.main.services.comet4j.impl;

import org.comet4j.core.CometContext;
import org.comet4j.core.CometEngine;
import org.goyo.main.comet4j.Comet4jConfig;
import org.goyo.main.comet4j.CometInit;
import org.goyo.main.comet4j.TaskMsgBean;
import org.goyo.main.domain.dao.comet4j.IComet4jDao;
import org.goyo.main.domain.entity.system.SysRoleResource;
import org.goyo.main.domain.entity.system.SysUser;
import org.goyo.main.services.comet4j.IComet4jService;
import org.goyo.main.services.system.ISystemService;
import org.goyo.main.web.controller.system.SessionUtil;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.session.SessionInformation;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import javax.annotation.Resource;
import javax.transaction.Transactional;


@Service
@Transactional
public class Comet4jServiceimpl implements IComet4jService {
  @Resource
  IComet4jDao comet4jDao;
  @Resource
  ISystemService systemService;
  @Resource
  SessionRegistry sessionRegistry;

  @Override
  public void sendAuditInfo() {
    SysUser user = null;
    user = (SysUser) SessionUtil.getAttribute("user");
    // Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
    // 获得当前用户所拥有的权限
    Set<GrantedAuthority> authorities = (Set<GrantedAuthority>) user.getAuthorities();
    // 通过url查找资源对应资源
    Map<String, List<SysRoleResource>> authoritys = systemService.getAllAuthority();
    Map<String, TaskMsgBean> tmMap = new HashMap<String, TaskMsgBean>();
    for (Map.Entry<String, List<SysRoleResource>> en : authoritys.entrySet()) {
      switch (en.getKey()) {
        case Comet4jConfig.AUDIT_TYPE_SALES_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_SALES_URL)) {
            createTask("SaleOrder", Comet4jConfig.AUDIT_TYPE_SALES_URL,
                Comet4jConfig.AUDIT_TYPE_SALES_JUMP_URL, Comet4jConfig.AUDIT_TYPE_SALES_JUMP_NAME,
                tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_PROCUREMENT_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_PROCUREMENT_URL)) {
            createTask("PurOrder", Comet4jConfig.AUDIT_TYPE_PROCUREMENT_URL,
                Comet4jConfig.AUDIT_TYPE_PROCUREMENT_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_PROCUREMENT_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_DISPATCH_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_DISPATCH_URL)) {
            createTask("Dispatch", Comet4jConfig.AUDIT_TYPE_DISPATCH_URL,
                Comet4jConfig.AUDIT_TYPE_DISPATCH_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_DISPATCH_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_URL)) {
            createTask("PurInStorage", Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_URL,
                Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_URL)) {
            createTask("SaleOutStorage", Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_URL,
                Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_URL)) {
            createTask("InventoryUnpack", Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_URL,
                Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_URL)) {
            createTask("InventoryCheck", Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_URL,
                Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        default:
          break;
      }
      tmMap.values();
      /*
       * CometEngine engine = CometContext.getInstance().getEngine();
       * engine.sendTo(CometInit.TASK_PROMPT
       * ,engine.getConnection(user.getMsgClientId()),org.goyo.common
       * .utils.JSONUtil.obj2Json(tmMap.values()));
       */
    }
  }

  public void createTask(String className, String auditTypeSalesUrl, String auditTypeSalesJumpUrl,
      String auditTypeSalesJumpName, Map<String, TaskMsgBean> tmMap,
      Entry<String, List<SysRoleResource>> en, Set<GrantedAuthority> authorities) {
    List<SysRoleResource> value = en.getValue();
    if (null != value) {
      for (GrantedAuthority grantedAuthority : authorities) {
        for (SysRoleResource sysRoleResource : value) {
          if (sysRoleResource.getRoleId().equals(grantedAuthority.getAuthority())) {
            /*Long re =
                comet4jDao.countByHql("select count(*) from " + className + " where status=3");*/
            List list = comet4jDao.findObjects("select uuid,submitUser.trueName, submitDate from "+className+" where status=3", null, null);
            if (list.size() < 1) {
              return;
            }
            for (Object object : list) {
              Object[] values = (Object[]) object;
              tmMap.put(auditTypeSalesUrl+"?uuid="+values[0], new TaskMsgBean(auditTypeSalesJumpUrl+"?uuid="+values[0],
                  auditTypeSalesJumpName,1l,values[1]+"",values[2]+""));
            }
            /*tmMap.put(auditTypeSalesUrl, new TaskMsgBean(auditTypeSalesJumpUrl,
                auditTypeSalesJumpName, re));*/
            return;
          }
        }
      }
    }
  }

  @Override
  public Long getInfoTotal() {
    SysUser user = null;
    user = (SysUser) SessionUtil.getAttribute("user");
    // Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
    // 获得当前用户所拥有的权限
    Set<GrantedAuthority> authorities = (Set<GrantedAuthority>) user.getAuthorities();
    // 通过url查找资源对应资源
    Map<String, List<SysRoleResource>> authoritys = systemService.getAllAuthority();
    Map<String, TaskMsgBean> tmMap = new HashMap<String, TaskMsgBean>();
    for (Map.Entry<String, List<SysRoleResource>> en : authoritys.entrySet()) {
      switch (en.getKey()) {
        case Comet4jConfig.AUDIT_TYPE_SALES_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_SALES_URL)) {
            createTask("SaleOrder", Comet4jConfig.AUDIT_TYPE_SALES_URL,
                Comet4jConfig.AUDIT_TYPE_SALES_JUMP_URL, Comet4jConfig.AUDIT_TYPE_SALES_JUMP_NAME,
                tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_PROCUREMENT_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_PROCUREMENT_URL)) {
            createTask("PurOrder", Comet4jConfig.AUDIT_TYPE_PROCUREMENT_URL,
                Comet4jConfig.AUDIT_TYPE_PROCUREMENT_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_PROCUREMENT_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_DISPATCH_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_DISPATCH_URL)) {
            createTask("Dispatch", Comet4jConfig.AUDIT_TYPE_DISPATCH_URL,
                Comet4jConfig.AUDIT_TYPE_DISPATCH_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_DISPATCH_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_URL)) {
            createTask("PurInStorage", Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_URL,
                Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_URL)) {
            createTask("SaleOutStorage", Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_URL,
                Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_URL)) {
            createTask("InventoryUnpack", Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_URL,
                Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_URL)) {
            createTask("InventoryCheck", Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_URL,
                Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        default:
          break;
      }

    }
    Long count = 0l;
    for (Map.Entry<String, TaskMsgBean> entry : tmMap.entrySet()) {
      count += entry.getValue().getNum();
    }
    return count;
  }

  @Override
  public List getInfoList() {
    SysUser user = null;
    user = (SysUser) SessionUtil.getAttribute("user");
    // Collection<? extends GrantedAuthority> authorities = user.getAuthorities();
    // 获得当前用户所拥有的权限
    Set<GrantedAuthority> authorities = (Set<GrantedAuthority>) user.getAuthorities();
    // 通过url查找资源对应资源
    Map<String, List<SysRoleResource>> authoritys = systemService.getAllAuthority();
    Map<String, TaskMsgBean> tmMap = new HashMap<String, TaskMsgBean>();
    for (Map.Entry<String, List<SysRoleResource>> en : authoritys.entrySet()) {
      switch (en.getKey()) {
        case Comet4jConfig.AUDIT_TYPE_SALES_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_SALES_URL)) {
            createTask("SaleOrder", Comet4jConfig.AUDIT_TYPE_SALES_URL,
                Comet4jConfig.AUDIT_TYPE_SALES_JUMP_URL, Comet4jConfig.AUDIT_TYPE_SALES_JUMP_NAME,
                tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_PROCUREMENT_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_PROCUREMENT_URL)) {
            createTask("PurOrder", Comet4jConfig.AUDIT_TYPE_PROCUREMENT_URL,
                Comet4jConfig.AUDIT_TYPE_PROCUREMENT_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_PROCUREMENT_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_DISPATCH_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_DISPATCH_URL)) {
            createTask("Dispatch", Comet4jConfig.AUDIT_TYPE_DISPATCH_URL,
                Comet4jConfig.AUDIT_TYPE_DISPATCH_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_DISPATCH_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_URL)) {
            createTask("PurInStorage", Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_URL,
                Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_PURINSTORAGE_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_URL)) {
            createTask("SaleOutStorage", Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_URL,
                Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_SALEOUTSTORAGE_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_URL)) {
            createTask("InventoryUnpack", Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_URL,
                Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_INVENTORYUNPACK_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        case Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_URL:
          if (null == tmMap.get(Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_URL)) {
            createTask("InventoryCheck", Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_URL,
                Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_JUMP_URL,
                Comet4jConfig.AUDIT_TYPE_INVENTORYCHECK_JUMP_NAME, tmMap, en, authorities);
          }
          break;
        default:
          break;
      }
    }
    CometEngine engine = CometContext.getInstance().getEngine();
    List<TaskMsgBean> relist = new ArrayList<TaskMsgBean>();
    Long count = 0l;
    for (Map.Entry<String, TaskMsgBean> entry : tmMap.entrySet()) {
      relist.add(entry.getValue());
      count+=entry.getValue().getNum();
    }
    engine.sendTo(CometInit.TASK_PROMPT,
        engine.getConnection(user.getMsgClientId()), count);
    return relist;
  }

  @Override
  public void sendTaskInfo(String AUDIT_URL, Long num) {
    List<SysUser> users = this.queryLoginUser();
    // 通过url查找资源对应资源
    Map<String, List<SysRoleResource>> authoritys = systemService.getAllAuthority();
    CometEngine engine = CometContext.getInstance().getEngine();
    for (SysUser user : users) {
      // 获得当前用户所拥有的权限
      Set<GrantedAuthority> authorities = (Set<GrantedAuthority>) user.getAuthorities();
      Map<String, TaskMsgBean> tmMap = new HashMap<String, TaskMsgBean>();
      for_start: for (Map.Entry<String, List<SysRoleResource>> en : authoritys.entrySet()) {
        if (en.getKey().equals(AUDIT_URL)) {
          if (null == tmMap.get(AUDIT_URL)) {
            List<SysRoleResource> values = en.getValue();
            if (null != values) {
              for (GrantedAuthority grantedAuthority : authorities) {
                for (SysRoleResource sysRoleResource : values) {
                  if (sysRoleResource.getRoleId().equals(grantedAuthority.getAuthority())) {
                    engine.sendTo(CometInit.TASK_PROMPT,
                        engine.getConnection(user.getMsgClientId()), num);
                    continue for_start;
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  private List<SysUser> queryLoginUser() {
    List<Object> slist = sessionRegistry.getAllPrincipals();
    int totalCount = slist.size();
    if (slist.size() == 0) {
      return null;
    }
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    List<Object> pageList = slist;
    List<SysUser> users = new ArrayList<SysUser>();
    for (int i = 0; i < pageList.size(); i++) {
      List<SessionInformation> sessionList = sessionRegistry.getAllSessions(pageList.get(i), true);
      SysUser user = (SysUser) pageList.get(i);
      users.add(user);
    }
    return users;
  }

}
